package com.itheima.reggie.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.itheima.reggie.common.R;

import com.itheima.reggie.dto.orderDto;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.entity.User;

import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrdersService;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

import java.net.URLEncoder;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrdersController {

    @Autowired
    OrdersService ordersService;

    @Autowired
    UserService userService;

    @Autowired
    OrderDetailService orderDetailService;

    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {

        ordersService.submit(orders);
        return R.success("清空购物车成功");
    }

    @GetMapping("/userPage")
    public R<Page> page(int page, int pageSize, HttpSession session) {
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        Page<orderDto>   objectPage = new Page<>();
        LambdaUpdateWrapper<Orders> ordersWrapper = new LambdaUpdateWrapper<>();

        ordersWrapper.orderByDesc(Orders::getOrderTime);
        User user = (User) session.getAttribute("user");
        ordersWrapper.eq(Orders::getUserId,user.getId());
        ordersService.page(ordersPage,ordersWrapper);

        LambdaUpdateWrapper<OrderDetail> qw = new LambdaUpdateWrapper<>();
        List<Orders> records = ordersPage.getRecords();

        List<orderDto> list1 = records.stream().map((item) -> {
            orderDto orderDto = new orderDto();
            Long orderId = item.getId();
            qw.eq(OrderDetail::getOrderId, orderId);

            List<OrderDetail> list = orderDetailService.list(qw);
            BeanUtils.copyProperties(item,orderDto);
            orderDto.setOrderDetails(list);
            return orderDto;
        }).collect(Collectors.toList());

        BeanUtils.copyProperties(ordersPage,objectPage,"records");
        objectPage.setRecords(list1);
        return R.success(objectPage);
    }

    @GetMapping("/page")
    public R pageR(int page, int pageSize, Long number, String beginTime,String endTime) {
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> qw = new LambdaQueryWrapper<>();
        qw.orderByDesc(Orders::getOrderTime);
        qw.like(number!=null,Orders::getId,number);
        qw.gt(beginTime!=null,Orders::getOrderTime,beginTime);
        qw.lt(endTime!=null,Orders::getOrderTime,endTime);
        Page<Orders> page1 = ordersService.page(ordersPage, qw);
        List<Orders> list = page1.getRecords();
        long total = page1.getTotal();
        List<Orders> orderDtos = list.stream().map((item) -> {
            Long userId = item.getUserId();
            User byId = userService.getById(userId);
            if (byId != null) {
                item.setUserName(byId.getName());
            }
            return item;
        }).collect(Collectors.toList());

        Map map = new HashMap();
        map.put("records", orderDtos);
        map.put("total", total);


        return R.success(map);

    }

    @GetMapping("/export")
    public void dowexsl(HttpServletResponse response) throws IOException {
        List<Orders> list = ordersService.list();
        ExcelWriter wirter = ExcelUtil.getWriter(true);
        //自定义标题别名（最后生成excel表格的名字），不然用数据库的字段名会很丑

        wirter.addHeaderAlias("number","订单号");
        wirter.addHeaderAlias("status","订单状态");
        wirter.addHeaderAlias("phone","手机号");
        wirter.addHeaderAlias("address","地址");
        wirter.addHeaderAlias("userName","用户名");
        //数据库中的下划线自动转驼峰
        wirter.addHeaderAlias("checkTime","下单时间");
        wirter.addHeaderAlias("amount","总额");

        //hutool默认的，未添加alias的属性也会写出，如果想只写出加了别名的字段，可以调用此方法排除之
        wirter.setOnlyAlias(true);
        wirter.write(list,true);
        //我们将输出的excel文件写出到客户端直接下载
        //response为HttpServletResponse对象
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
//       response.setHeader("Content-Disposition","attachment;filename=test.xls");
        String fileName = URLEncoder.encode("订单明细","UTF-8");
        response.setHeader("Content-Disposition","attachment;filename="+fileName+".xlsx");
        ServletOutputStream out=response.getOutputStream();
        wirter.flush(out,true);
        //关闭wirter，释放内存
        wirter.close();
        //关机输出servlet流
        IoUtil.close(out);

    }


}
